package com.zjgsu.nftplatform.service.impl;
/*
 * @author jChen
 * @date 2022/4/21 11:00
 * @detail:
 */

import cn.hutool.core.lang.Assert;
import com.zjgsu.nftplatform.client.BlockchainClient;
import com.zjgsu.nftplatform.pojo.Result;
import com.zjgsu.nftplatform.pojo.ResultCode;
import com.zjgsu.nftplatform.service.FileUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    private static final List<String>  coverExtension = new ArrayList<>(Arrays.asList(".jpeg", ".jpg", ".png", ".gif"));
    @Value("${file.nginxDir}")
    private String nginxDir;
    @Value("${file.saveDir}")
    private String saveDir;
    @Value("${myurl.server}")
    private String url;

    private final BlockchainClient blockchainClient;

    public FileUploadServiceImpl(BlockchainClient blockchainClient) {
        this.blockchainClient = blockchainClient;
    }

    @Override
    public String fileUpload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!coverExtension.contains(extension)){
            return null;
        }else {
            String newFileName = UUID.randomUUID() + extension;
            String newFilePath = nginxDir + saveDir + newFileName;
            File upDir = new File(newFilePath.substring(0, newFilePath.lastIndexOf("/")));
            if (!upDir.exists()){
                if (!upDir.mkdirs()){
                    return null;
                }
            }
            file.transferTo(new File(upDir, newFileName));
            return "http://" + url + saveDir + newFileName;
        }
    }

    @Override
    public String upload(MultipartFile file) {
        Result result = blockchainClient.addFIle2Ipfs(file);
        Assert.isTrue(result.getCode() == ResultCode.SUCCESS.getCode(), "请求上传文件到IPFS失败");
        String fileHash = (String) result.getData();
        return fileHash.replace("\n", "");
    }
}
